package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.cloudbroker.bcs.common.model.Pagination;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.CombDetailResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.FocusCombineResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.SubscriptionCombineResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.UserTransferQryResult;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedSecT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.CombDetailForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.FocusCombineForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.SubscriptionCombineForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.interestRelated.UserTransferQryForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.CombDetailQryBackVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.FocusCombineQryBackVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.SubscriptionCombineQryBackVo;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.UserTransferQryBackVo;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.ltb.bizapi.constants.type.MsgType;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.UserEntityVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.MsgBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.vo.MsgCombineDetailForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.vo.MsgCombineDetailListForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.vo.MsgDetailListForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.msg.vo.MsgIndexForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UsersQueryVo;
import com.cloudbroker.bcs.platform.ltb.middle.entity.AppUserTags;
import com.cloudbroker.bcs.platform.ltb.middle.entity.Msg;
import com.cloudbroker.bcs.platform.ltb.middle.entity.MsgReadRecord;
import com.cloudbroker.bcs.platform.ltb.middle.entity.UserEntity;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.MsgGroupCountParam;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.MsgGroupCountView;
import com.cloudbroker.bcs.platform.ltb.middle.entityview.MsgListParam;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.service.AppUserTagService;
import com.cloudbroker.bcs.platform.ltb.middle.service.MsgReadRecordService;
import com.cloudbroker.bcs.platform.ltb.middle.service.MsgService;
import com.cloudbroker.bcs.platform.ltb.middle.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by daibd19671 on 2016/12/28.
 */
@Service
public class MsgBizServiceImpl implements MsgBizService{

    @Resource
    private MsgService msgService;
    @Resource
    private LedT2Service ledT2Service;
    @Resource
    private LedSecT2Service ledSecT2Service;
    @Resource
    private MsgReadRecordService msgReadRecordService;
    @Resource
    private AppUserTagService appUserTagService;

    @Resource
    private UserService userService;
    @Resource
    private UserCenterService userCenterService;

    @Override
    public MsgIndexBack msg_index(MsgIndexForm form) {
        if(form.getUser()!=null){
            MsgReadRecord msgReadRecord = new MsgReadRecord();
            msgReadRecord.setCompany_id(form.getCompany_id());
            msgReadRecord.setUser_id(form.getUser().getUser_id());
            List<MsgReadRecord> recordList = msgReadRecordService.query(msgReadRecord);
            if(recordList == null || recordList.size()==0 || recordList.size()!=MsgType.values().length){
                this.initMsgReadTime(form.getUser().getUser_id(),form.getCompany_id(),recordList);
            }
        }
        MsgGroupCountParam param = new MsgGroupCountParam();
        param.setCurrent_time(System.currentTimeMillis());
        param.setCompany_id(form.getCompany_id());
        if (form.getUser() != null) {
            param.setUser_id(form.getUser().getUser_id());
            //获取关注的组合
            FocusCombineForm focusCombineForm = new FocusCombineForm();
            focusCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
            focusCombineForm.setUser_token(form.getUser_token());
            FocusCombineQryBackVo combineBack = ledT2Service.func_combine_collect_info_qry(focusCombineForm);
            if (!VOUtil.isSuccess(combineBack)) {
                return VOUtil.genBGErrorResult(combineBack.getError_no(), combineBack.getError_info(), MsgIndexBack.class);
            }
            //获取收藏的组合列表
            SubscriptionCombineForm subscriptionCombineForm = new SubscriptionCombineForm();
            subscriptionCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
            subscriptionCombineForm.setUser_token(form.getUser_token());
            SubscriptionCombineQryBackVo subscriptionCombineQryBackVo = ledT2Service.func_comb_subscription(subscriptionCombineForm);
            if (!VOUtil.isSuccess(subscriptionCombineQryBackVo)) {
                return VOUtil.genBGErrorResult(subscriptionCombineQryBackVo.getError_no(), subscriptionCombineQryBackVo.getError_info(), MsgIndexBack.class);
            }
            List<FocusCombineResult> focusCombineList = combineBack.getData_list();
            List<SubscriptionCombineResult> subCombineList = subscriptionCombineQryBackVo.getData_list();
            int size = (focusCombineList == null ? 0 : focusCombineList.size())
                    + (subCombineList == null ? 0 : subCombineList.size());
            List<String> codeList = new ArrayList<>(size);
            if (focusCombineList != null) {
                for (FocusCombineResult result : focusCombineList) {
                    codeList.add(result.getCombi_code());
                }
            }
            if (subCombineList != null) {
                for (SubscriptionCombineResult result : subCombineList) {
                    if (!codeList.contains(result.getCombi_code())) {
                        codeList.add(result.getCombi_code());
                    }
                }
            }
//        List<String> codeList = new ArrayList<>();
//        codeList.add("111111");
//        codeList.add("222222");
//        codeList.add("333333");
            param.setCodeList(codeList);

            //获取标签列表
            AppUserTags appUserTags = new AppUserTags();
            appUserTags.setApp_user_id(form.getUser().getUser_id());
            appUserTags.setCompany_id(form.getCompany_id());
            appUserTags.setSendercomp_id(form.getSendercomp_id());
            List<AppUserTags> tags = appUserTagService.queryAppUserTag(appUserTags);
            List<String> tagList = new ArrayList<>();
            for (AppUserTags tag : tags) {
                tagList.add(tag.getTag());
            }
            param.setTag(tagList);
        }
        List<MsgGroupCountView> list = msgService.groupCount(param);
        List<Msg> lastMsg = msgService.groupLastMsg(param);
        List<MsgIndexResult> backList = new ArrayList<>(MsgType.values().length);
        for(MsgType type : MsgType.values()){
            MsgIndexResult result = new MsgIndexResult();
            result.setMsg_type(type.getVal());
            if(list!=null && list.size()>0){
                for(MsgGroupCountView view : list) {
                    if(view.getMsg_type() != type.getVal()){
                        continue;
                    }
                    result.setMsg_count(view.getMsg_count());
                }
            }else{
                result.setMsg_count(0);
            }
            for(Msg last : lastMsg){
                if(last.getMsg_type() != type.getVal()){
                    continue;
                }
                result.setMsg_content(last.getMsg_content());
            }
            backList.add(result);
        }
        MsgIndexBack back = new MsgIndexBack();
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }

    @Override
    public MsgDetailListBack msg_detail_list(MsgDetailListForm form) {
        if(!chechMsgType(form)){
            return VOUtil.genErrorResult(HSBCPSErrorCodes.PushErrorInfo.MSG_TYPE_ERR,MsgDetailListBack.class);
        }
        MsgListParam msgParam = new MsgListParam();
        msgParam.setCurrent_time(System.currentTimeMillis());
        if(form.getUser()!=null){
            msgParam.setUser_id(form.getUser().getUser_id());
        }
        msgParam.setMsg_type(form.getMsg_type());
        msgParam.setCompany_id(form.getCompany_id());
        Pagination pagination = new Pagination();
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        msgParam.setPage(pagination);
        if (form.getUser() != null) {
            if (form.getMsg_type() == MsgType.COMBINE.getVal()) {
                //获取关注的组合
                FocusCombineForm focusCombineForm = new FocusCombineForm();
                focusCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
                focusCombineForm.setUser_token(form.getUser_token());
                FocusCombineQryBackVo combineBack = ledT2Service.func_combine_collect_info_qry(focusCombineForm);
                if (!VOUtil.isSuccess(combineBack)) {
                    return VOUtil.genBGErrorResult(combineBack.getError_no(), combineBack.getError_info(), MsgDetailListBack.class);
                }
                //获取收藏的组合列表
                SubscriptionCombineForm subscriptionCombineForm = new SubscriptionCombineForm();
                subscriptionCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
                subscriptionCombineForm.setUser_token(form.getUser_token());
                SubscriptionCombineQryBackVo subscriptionCombineQryBackVo = ledT2Service.func_comb_subscription(subscriptionCombineForm);
                if (!VOUtil.isSuccess(subscriptionCombineQryBackVo)) {
                    return VOUtil.genBGErrorResult(subscriptionCombineQryBackVo.getError_no(), subscriptionCombineQryBackVo.getError_info(), MsgDetailListBack.class);
                }
                List<FocusCombineResult> focusCombineList = combineBack.getData_list();
                List<SubscriptionCombineResult> subCombineList = subscriptionCombineQryBackVo.getData_list();
                int size = (focusCombineList == null ? 0 : focusCombineList.size())
                        + (subCombineList == null ? 0 : subCombineList.size());
                List<String> codeList = new ArrayList<>(size);
                if (focusCombineList != null) {
                    for (FocusCombineResult result : focusCombineList) {
                        codeList.add(result.getCombi_code());
                    }
                }
                if (subCombineList != null) {
                    for (SubscriptionCombineResult result : subCombineList) {
                        if (!codeList.contains(result.getCombi_code())) {
                            codeList.add(result.getCombi_code());
                        }
                    }
                }
//            List<String> codeList = new ArrayList<>();
//            codeList.add("111111");
//            codeList.add("222222");
//            codeList.add("333333");
                msgParam.setCodeList(codeList);
            } else {
                //获取所有tag
                AppUserTags appUserTags = new AppUserTags();
                appUserTags.setApp_user_id(form.getUser().getUser_id());
                appUserTags.setCompany_id(form.getCompany_id());
                appUserTags.setSendercomp_id(form.getSendercomp_id());
                List<AppUserTags> tags = appUserTagService.queryAppUserTag(appUserTags);
                List<String> tagList = new ArrayList<>();
                for (AppUserTags tag : tags) {
                    tagList.add(tag.getTag());
                }
                msgParam.setTag(tagList);
            }
        }
        List<Msg> list = new ArrayList<>();
        if (form.getMsg_type() == MsgType.COMBINE.getVal()) {
            list = msgService.queryCombine(msgParam);
        } else {
            list = msgService.queryByType(msgParam);
        }
        List<MsgDetailListResult> resultList = new ArrayList<>(list.size());
        for (Msg temp : list) {
            MsgDetailListResult result = new MsgDetailListResult();
            BeanUtils.copyProperties(temp, result);
            result.setMsg_time(temp.getCreate_time());
            resultList.add(result);
        }
        MsgDetailListBack back = new MsgDetailListBack();
        back.setData_list(resultList);
        if (form.getUser() != null) {
            this.recordMsgReadTime(form.getUser().getUser_id(), form.getMsg_type(), form.getCompany_id());
        }
        return VOUtil.setSuccessResult(back);
    }
    private boolean chechMsgType(MsgDetailListForm form) {
        if (form.getMsg_type() != MsgType.COMBINE.getVal() &&
                form.getMsg_type() != MsgType.ACTIVITY.getVal() &&
                form.getMsg_type() != MsgType.ASK.getVal() &&
                form.getMsg_type() != MsgType.SYSTEM.getVal()) {
            return false;
        }
        return true;
    }

    /**
     * 初始化时间记录表数据
     * @param user_id
     */
    private void initMsgReadTime(long user_id,String company_id,List<MsgReadRecord> recordList){
        Map<Integer,MsgReadRecord> map = new HashMap<>();
        for(MsgReadRecord record : recordList){
            map.put(record.getMsg_type(),record);
        }
        List<MsgReadRecord> addList = new ArrayList<>();
        for(MsgType type : MsgType.values()){
            if(!map.containsKey(type.getVal())){
                MsgReadRecord qryRecord = new MsgReadRecord();
                qryRecord.setCompany_id(company_id);
                qryRecord.setUser_id(user_id);
                qryRecord.setMsg_type(type.getVal());
                qryRecord.setRead_time(0L);
                addList.add(qryRecord);
            }
        }
        if(addList.size()>0){
            msgReadRecordService.addList(addList);
        }
    }

    /**
     * 记录消息阅读时间
     * @param user_id
     * @param msgType
     */
    @Transactional
    private void recordMsgReadTime(long user_id,int msgType,String company_id){
        MsgReadRecord temp = new MsgReadRecord();
        temp.setCompany_id(company_id);
        temp.setUser_id(user_id);
        temp.setMsg_type(msgType);
        MsgReadRecord mrr = msgReadRecordService.getByEntity(temp);
        if(mrr == null){
            temp.setRead_time(new Date().getTime());
            msgReadRecordService.save(temp);
        }else{
            mrr.setRead_time(new Date().getTime());
            msgReadRecordService.update(mrr);
        }
    }


    @Override
    public MsgCombineDetailListBack msg_combine_list(MsgCombineDetailListForm form) {
        MsgListParam msgParam = new MsgListParam();
        msgParam.setUser_id(form.getUser().getUser_id());
        msgParam.setMsg_type(MsgType.COMBINE.getVal());
        msgParam.setCompany_id(form.getCompany_id());
        Pagination pagination = new Pagination();
        pagination.setStart_index(form.getStart_row());
        pagination.setPage_size(form.getRequest_num());
        msgParam.setPage(pagination);
        //获取关注的组合
        FocusCombineForm focusCombineForm = new FocusCombineForm();
        focusCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        focusCombineForm.setUser_token(form.getUser_token());
        FocusCombineQryBackVo combineBack = ledT2Service.func_combine_collect_info_qry(focusCombineForm);
        if (!VOUtil.isSuccess(combineBack)) {
            return VOUtil.genBGErrorResult(combineBack.getError_no(), combineBack.getError_info(), MsgCombineDetailListBack.class);
        }
        //获取收藏的组合列表
        SubscriptionCombineForm subscriptionCombineForm = new SubscriptionCombineForm();
        subscriptionCombineForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        subscriptionCombineForm.setUser_token(form.getUser_token());
        SubscriptionCombineQryBackVo subscriptionCombineQryBackVo = ledT2Service.func_comb_subscription(subscriptionCombineForm);
        if (!VOUtil.isSuccess(subscriptionCombineQryBackVo)) {
            return VOUtil.genBGErrorResult(subscriptionCombineQryBackVo.getError_no(), subscriptionCombineQryBackVo.getError_info(), MsgCombineDetailListBack.class);
        }
        List<FocusCombineResult> focusCombineList = combineBack.getData_list();
        List<SubscriptionCombineResult> subCombineList = subscriptionCombineQryBackVo.getData_list();
        int size = (focusCombineList == null ? 0 : focusCombineList.size())
                + (subCombineList == null ? 0 : subCombineList.size());
        List<String> codeList = new ArrayList<>(size);
        if (focusCombineList != null) {
            for (FocusCombineResult result : focusCombineList) {
                codeList.add(result.getCombi_code());
            }
        }
        if (subCombineList != null) {
            for (SubscriptionCombineResult result : subCombineList) {
                if (!codeList.contains(result.getCombi_code())) {
                    codeList.add(result.getCombi_code());
                }
            }
        }
        msgParam.setCodeList(codeList);
        List<Msg> list = msgService.queryCombine(msgParam);
        MsgCombineDetailListBack back = new MsgCombineDetailListBack();
        List<MsgCombineDetailListResult> backList = new ArrayList<>(list.size());
        for(Msg m : list){
            CombDetailForm combDetailForm = new CombDetailForm();
            combDetailForm.setOp_branch_no(form.getOp_branch_no());
            combDetailForm.setOp_entrust_way(form.getOp_entrust_way());
            combDetailForm.setOp_station(form.getOp_station());
            combDetailForm.setBranch_no(form.getBranch_no());
            combDetailForm.setPassword(form.getPassword());
            combDetailForm.setPassword_type(form.getPassword_type());
            combDetailForm.setUser_token(form.getUser_token());
            combDetailForm.setSendercomp_id(form.getSendercomp_id());
            combDetailForm.setCombi_code(m.getCombine_code());
            CombDetailQryBackVo combDetailQryBackVo = ledT2Service.func_comb_details(combDetailForm);
            MsgCombineDetailListResult result = new MsgCombineDetailListResult();
            if(combDetailQryBackVo.getData_list()!=null) {
                for (CombDetailResult combiResult : combDetailQryBackVo.getData_list()) {
                    result.setCombi_code(combiResult.getCombi_code());
                    result.setCombi_name(combiResult.getCombi_name());
                    result.setIncome_ratio(combiResult.getIncome_ratio());
                    result.setMsg_time(m.getCreate_time());
                    UsersQueryVo usersQueryVo = userCenterService.func_users_query(combiResult.getUser_id());
                    if(VOUtil.isSuccess(usersQueryVo)
                            && usersQueryVo.getData_list()!=null
                            && usersQueryVo.getData_list().size()>0){
                        result.setLeader_avatar(usersQueryVo.getData_list().get(0).getAvatar());
                    }
                }
            }
            backList.add(result);
        }
        back.setData_list(backList);
        this.recordMsgReadTime(form.getUser().getUser_id(),MsgType.COMBINE.getVal(),form.getCompany_id());
        return VOUtil.setSuccessResult(back);
    }

    @Override
    public MsgCombineDetailBack msg_combine_detail(MsgCombineDetailForm form) {
        //查询组合基本信息
        CombDetailForm combDetailForm = new CombDetailForm();
        combDetailForm.setOp_branch_no(form.getOp_branch_no());
        combDetailForm.setOp_entrust_way(form.getOp_entrust_way());
        combDetailForm.setOp_station(form.getOp_station());
        combDetailForm.setBranch_no(form.getBranch_no());
        combDetailForm.setPassword(form.getPassword());
        combDetailForm.setPassword_type(form.getPassword_type());
        combDetailForm.setUser_token(form.getUser_token());
        combDetailForm.setSendercomp_id(form.getSendercomp_id());
        combDetailForm.setCombi_code(form.getCombi_code());
        CombDetailQryBackVo combDetailQryBackVo = ledT2Service.func_comb_details(combDetailForm);
        if (!VOUtil.isSuccess(combDetailQryBackVo)) {
            return VOUtil.genBGErrorResult(combDetailQryBackVo.getError_no(), combDetailQryBackVo.getError_info(), MsgCombineDetailBack.class);
        }
        if (combDetailQryBackVo.getData_list() == null || combDetailQryBackVo.getData_list().size() == 0) {
            return VOUtil.setSuccessResult(new MsgCombineDetailBack());
        }
        UserEntity userEntity = null;
        CombDetailResult combiResult = null;
        for (CombDetailResult result : combDetailQryBackVo.getData_list()) {
            combiResult = result;
            userEntity = userService.get(combiResult.getUser_id());
        }
        List<MsgCombineDetailResult> backList = new ArrayList<>();
        //查询组合历史调仓
        UserTransferQryForm userTransferQryForm = new UserTransferQryForm();
//        userTransferQryForm.setOp_branch_no(form.getOp_branch_no());
        userTransferQryForm.setOp_entrust_way(form.getOp_entrust_way());
        userTransferQryForm.setOp_station(form.getOp_station());
//        userTransferQryForm.setBranch_no(form.getBranch_no());
        userTransferQryForm.setPassword("111111");
        userTransferQryForm.setPassword_type("1");
        userTransferQryForm.setUser_token(form.getUser_token());
        userTransferQryForm.setSendercomp_id(form.getSendercomp_id());
        userTransferQryForm.setCompany_id("91000");
        userTransferQryForm.setAasexch_type("A01");
        userTransferQryForm.setBusinsys_no(combiResult.getBusinsys_no());
        userTransferQryForm.setBusin_account(combiResult.getBusin_account());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        long begin_date = 20160101;
        long end_date = Integer.valueOf(sdf.format(new Date()));
        userTransferQryForm.setBegin_date(begin_date);
        userTransferQryForm.setEnd_date(end_date);
        UserTransferQryBackVo userTransferQryBackVo = ledSecT2Service.func_user_transfer_qry(userTransferQryForm);
        if (!VOUtil.isSuccess(userTransferQryBackVo)) {
            return VOUtil.genBGErrorResult(userTransferQryBackVo.getError_no(), userTransferQryBackVo.getError_info(), MsgCombineDetailBack.class);
        }
        List<UserTransferQryResult>  userTransferQryResultList = userTransferQryBackVo.getData_list();
        if (userTransferQryResultList != null && userTransferQryResultList.size() != 0) {
            if (userTransferQryResultList != null && userTransferQryResultList.size() > 0) {
                for (UserTransferQryResult result : userTransferQryResultList) {
                    MsgCombineDetailResult detail = new MsgCombineDetailResult();
                    detail.setCombi_code(form.getCombi_code());
                    detail.setCombi_name(combiResult.getCombi_name());
                    detail.setIncome_ratio(combiResult.getIncome_ratio());
                    detail.setEntrust_bs(result.getEntrust_bs());
                    detail.setProd_code(result.getProd_code());
                    detail.setProd_name(result.getProd_name());
                    detail.setBusiness_price(result.getBusiness_price());
                    detail.setBusiness_amount(result.getBusiness_amount());
                    SimpleDateFormat busSdf = new SimpleDateFormat("yyyyMMddHHmmss");
                    String dateStr = result.getInit_date().toString()+result.getBusiness_time().toString();
                    try {
                        detail.setBusiness_time(busSdf.parse(dateStr).getTime());
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                    if (userEntity != null) {
                        detail.setLeader_avatar(userEntity.getAvatar());
                    }
                    backList.add(detail);
                }
            }
        }
        MsgCombineDetailBack back = new MsgCombineDetailBack();
        back.setData_list(backList);
        return VOUtil.setSuccessResult(back);
    }
}
